import { createWebHashHistory, createRouter, RouteRecordRaw } from "vue-router"
import Login from "@/views/Login/index.vue"
import Home from "@/views/Home/index.vue"
import { useUserStore } from "@/store"
import { userInfoApi } from "@/request/api"
import { ElMessage } from 'element-plus'
const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        component: Login
    }, {
        path: "/",
        redirect: "/index"
    },
    {
        path: "/",
        component: () => import("@/views/Home/index.vue"),
        children: [
            {
                path: "index",
                component: () => import("@/views/Home/components/index.vue"),
            },
        ],
    },
]
const router = createRouter({
    routes,
    history: createWebHashHistory()
})

// 在路由守卫请求数据
router.beforeEach((to, from, next) => {
    const store = useUserStore()
    let token = localStorage.getItem("token")
    if (store.menus.length === 0 && token) {
        userInfoApi().then((res) => {
            if (res.code == 200) {
                store.menus = res.data.menus
                store.username = res.data.username
                store.routes.forEach((p) => {
                    const route: RouteRecordRaw = ({
                        path: "/" + p.name,
                        name: p.name,
                        component: () => import("@/views/Home/index.vue"),
                        meta: {
                            title: p.title
                        },
                        children: p.children.map((item) => ({
                            path: item.name,
                            name: item.name,
                            component: () => import(`../views/${p.name}/${item.name}.vue`),
                            meta: {
                                title: item.title
                            }
                        }))
                    })

                    if (p.children[0]) {
                        route.redirect = `/${p.name}/${p.children[0]?.name}`
                    }
                    router.addRoute(route)
                })
                next(to.fullPath);
            }
        })
    } else if (!token && to.path !== "/login") {
        // 判断有无token，没有的话，如果访问的不是登录页面则跳到登录页
        ElMessage.error("请先登录")
        next('login')
    }
    //不能直接跳去登录页 
    else if (token && store.menus.length !== 0 && to.path === "/login") {
        ElMessage.warning("请退出登录再返回登录页面")
        next(from.fullPath)
    } else {
        next()
    }
})
export default router